package itbour.onetouchshow.activity.searchlist;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.adapter.BaseRecyclerHolder;
import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.login.LoginActivity;
import itbour.onetouchshow.activity.preview.verticalpreview.verticalmodel.VerticalmodelActivity;
import itbour.onetouchshow.activity.userinfo.FeedBackActivity;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.BaseRefreshFragment;
import itbour.onetouchshow.bean.SearchListBean;
import itbour.onetouchshow.bean.page.Page;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.DataPlatform;
import itbour.onetouchshow.constants.platform.SearchPlatform;
import itbour.onetouchshow.listener.MyRyItemListener;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.JumpUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class SearchListFragment extends BaseRefreshFragment<SearchListContract.View, SearchListPresenter> implements SearchListContract.View {


    public Page page;
    public String keyword;
    public String durations;
    public String tmplTypes;
    public int orderBy = 1;
    public int showTypes = SearchPlatform.TYPE_DESIGN;
    //    PHEmptyDataSet phEmptyDataSet;
    List<SearchListBean.ListBean> mdata = new ArrayList<>();
    boolean isNoData;
    private SearchListBean searchListBean;
    private int totalPage;


    public SearchListFragment() {
    }

    public void onLoadData() {
        page = new Page() {
            @Override
            public void load(int param1, int param2) {
                L_.e("load" + param1);
                mPageIndex = param1;
                mPresenter.loadSearch(SearchListFragment.this, keyword, orderBy, showTypes, tmplTypes, durations);
            }
        };
        pullStatus = ON_REFRESH;
        if (mPresenter != null) {
            page.loadPage(true);
        }
    }


    @Override
    public void loadSucceed(String result) {
        if (xRefreshView.isEmptyViewShowing()) {
            xRefreshView.enableEmptyView(false);
        }
        showContentView();
        page.finishLoad(true);
        searchListBean = new Gson().fromJson(result, SearchListBean.class);
        List<SearchListBean.ListBean> resultData = searchListBean.getList();
        totalPage = searchListBean.getTotalPage();
        endNetRequse(resultData);
    }

    public void endNetRequse(List<SearchListBean.ListBean> data) {
        if (pullStatus == ON_LOAD) {
            mdata.addAll(data);
            xRefreshView.stopLoadMore();
        } else if (pullStatus == ON_REFRESH) {
            mdata = data;
            xRefreshView.stopRefresh();
        }
        if (totalPage == 1 || mPageIndex >= totalPage - 1) {
            xRefreshView.setLoadComplete(true);
        } else {
            xRefreshView.setLoadComplete(false);
        }
        baseRefreshAdapter.notifyDataSetChanged(mdata);
        pullStatus = 0;
    }


    @Override
    public void loadFaild(String error) {
        L_.e(error);
        page.finishLoad(false);
        if (error.equals("没有数据")) {
            showContentView();
            stopXfresh();
            if (!xRefreshView.isEmptyViewShowing()) {
                View noDataView = UIUtils.inflate(R.layout.no_search_data);
                xRefreshView.setEmptyView(noDataView);
                xRefreshView.enableEmptyView(true);
                noDataView.findViewById(R.id.id_user_greement).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (App.isLogin()) {
                            openActivity(FeedBackActivity.class);
                        } else {
                            openActivity(LoginActivity.class);
                        }

                    }
                });
            }
        } else {
            View noDataView = UIUtils.inflate(R.layout.view_network_error);
            xRefreshView.setEmptyView(noDataView);
            xRefreshView.enableEmptyView(true);
        }

    }

    @Override
    public void onRefresh() {
        super.onRefresh();
    }


    @Override
    protected void initView() {
        super.initView();
        pullStatus = ON_REFRESH;
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                pullStatus = ON_REFRESH;
                if (mPresenter != null) {
                    page.loadPage(true);
                }
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pullStatus = ON_LOAD;
                        if (mPresenter != null) {
                            page.loadPage(false);
                        }
                    }
                }, AppConst.DELAYED_TIME);

            }
        });

    }

    @Override
    public void initRecycleView() {
        baseRefreshAdapter = getBaseRefreshAdapter();
        if (baseRefreshAdapter == null) {
            return;
        }
        baseRefreshAdapter.setCustomLoadMoreView(new XRefreshViewFooter(getActivity()));
        recyclerView.setHasFixedSize(true);
        //使用瀑布流布局,第一个参数 spanCount 列数,第二个参数 orentation 排列方向
        StaggeredGridLayoutManager recyclerViewLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(recyclerViewLayoutManager);
        baseRefreshAdapter.setHeaderView(getHeadView(), recyclerView);
        recyclerView.setAdapter(baseRefreshAdapter);
        baseRefreshAdapter.setOnItemClickListener(new MyRyItemListener<SearchListBean.ListBean>() {
            @Override
            public void onItemSelect(SearchListBean.ListBean o) {

                int opType = o.getOpType();
                switch (opType) {
                    case DataPlatform.ORTYPE_VERTICAL:
                        Intent itToVertical = new Intent(getActivity(), VerticalmodelActivity.class);
//                        int postion = mdata.indexOf(o);
//                        itToVertical.putExtra("pageContentList", new Gson().toJson(mdata));
//                        itToVertical.putExtra("postion", postion);
                        ArrayList<SearchListBean.ListBean> listBeans = new ArrayList<>();
                        listBeans.add(o);
                        itToVertical.putExtra("pageContentList", new Gson().toJson(listBeans));
                        itToVertical.putExtra("postion", 0);
                        getActivity().startActivity(itToVertical);

                        break;
                    case DataPlatform.ORTYPE_VIDIO:
                        //Bundle bundle = IntentCode.getBundle(o.getId(), WorkPlatform.MODULE);
                        // openActivity(VideoplayActivity1.class, bundle);

                        JumpUtils.goToVideoPlayer(getActivity(), o.getId());

                        break;
                    case DataPlatform.ORTYPE_PPT:
                        break;
                    default:
                        break;
                }
            }
        });

    }


    @Override
    public BaseRefreshAdapter getBaseRefreshAdapter() {
        return baseRefreshAdapter = new SearchListAdapter(getActivity(), mdata, R.layout.item_search_list_adapter);
    }

    @Override
    public View getHeadView() {
        return null;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


//        phEmptyDataSet = new PHEmptyDataSet(getView());
//        phEmptyDataSet.setDelegate(new PHEmptyDataSet.EmptyDataSetDelegate() {
//            @Override
//            public View customView() {
//                View view1 = UIUtils.inflate(R.layout.no_search_data);
//                view1.findViewById(R.id.id_user_greement).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        openActivity(FeedBackActivity.class);
//                    }
//                });
//                return view1;
//            }
//        });
//        if (isNoData) {
//            showContentView();
//            phEmptyDataSet.noData();
//        }
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        if (mPresenter == null) {
            mPresenter = new SearchListPresenter(this);
        }
        Bundle extras = getActivity().getIntent().getExtras();
        isNoData = false;
        if (extras != null) {
            keyword = extras.getString("keywork");
            isNoData = extras.getBoolean("noData");
        }
        showLoadingView();
        onLoadData();
    }

    public class SearchListAdapter extends BaseRefreshAdapter<SearchListBean.ListBean> {

        public SearchListAdapter(Context context, List<SearchListBean.ListBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder viewHolder, SearchListBean.ListBean listBean, int position) {
            ImageView imageView = viewHolder.getView(R.id.id_ig);
            TextView tvName = viewHolder.getView(R.id.id_tv_name);
            TextView tvCount = viewHolder.getView(R.id.id_tv_count);
            TextView type = viewHolder.getView(R.id.id_tv_type);
            type.setVisibility(View.VISIBLE);
            ImageView vip = viewHolder.getView(R.id.iv_vip_template);
            vip.setVisibility(listBean.isVipTemplate() ? View.VISIBLE : View.GONE);

            int width = (UIUtils.WHD()[0]) / 2 - UIUtils.dp2px(10);
            int height = width * listBean.getH() / listBean.getW();
            String imUrl = ImageLoader.getShrinkImageUrl(listBean.getThumb(), width, height);
            // imageView.setInitSize(listBean.getW(),listBean.getH());
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
            layoutParams.width = width;
            layoutParams.height = height;

            ImageLoader.getInstance().showCircleImageWithBorder(getActivity(), imUrl, imageView);
            tvName.setText(listBean.getName());
            tvCount.setText(listBean.getUseCounts() + "人使用");
            type.setText(listBean.getTypeDesc());
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemSelect(listBean);
                    }
                }
            });
        }
    }

}
